#include <iostream>
#include <string>
#include <unistd.h>
#include "mysql.h"

const std::string host = "127.0.0.1";
const std::string user = "ts";
const std::string passwd = "FSFgudg!@#5_$@3dgdkdg342343";
const std::string db = "db_test2";
unsigned int port = 3306;

int main()
{
    // std::cout << mysql_get_client_info() << std::endl;
    // std::cout << "hello world" << std::endl;
    // 1.创建mysql句柄
    MYSQL *mfp = mysql_init(nullptr);
    // 2.链接数据库
    if (nullptr == mysql_real_connect(mfp, host.c_str(), user.c_str(),
                                      passwd.c_str(), db.c_str(), port, nullptr, 0))
    {
        std::cerr << "connect failed!" << std::endl;
        return 1;
    }
    // mysql_set_character_set(mfp, "utf8");
    mysql_set_character_set(mfp, "utf8");
    std::cout << "connect success!" << std::endl;

    // 3.数据库操作
    // 增加，删除，更改比较简单
    // std::string sql = "insert into stu values(5,'唐僧')";
    // std::string sql = "insert into stu values(5,'唐僧')";
    // std::string sql = "delete from stu where id=5";
    // std::string sql = "update stu set name='八戒' where id=1";
    // 查询来说相对较难
    std::string sql = "select * from stu";
    int ret = mysql_query(mfp, sql.c_str());
    if (ret != 0)
    {
        std::cout << "execute " << sql << " failed!" << std::endl;
    }
    else
    {
        std::cout << "execute " << sql << " success!" << std::endl;
        // 该函数malloc了一片内存空间来存储查询过来的数据
        MYSQL_RES *result = mysql_store_result(mfp);
        int row = mysql_num_rows(result);
        int col = mysql_num_fields(result);
        std::cout << "row:" << row << " col:" << col << std::endl;
        MYSQL_FIELD* fields = mysql_fetch_field(result);
        for(int i = 0; i < col; ++i)
        {
            std::cout << fields[i].name <<  "\t";
        }
        std::cout << std::endl;

        for(int i = 0; i < row; ++i)
        {
             //获取完整的一行记录[可能包含了多列]
            MYSQL_ROW line = mysql_fetch_row(result);
            for(int j = 0; j < col; ++j)
            {
                std::cout << line[j] << "\t"; //将记录内部的多列字符串依次打印！
            }
            std::cout << std::endl;
        }

        free(result);
    }
    // sleep(30);
    // 4.关闭数据接口
    mysql_close(mfp);
    return 0;
}